<template>
  <div id="app">
    <button @click="startRequest">测试异步通信（异常处理）</button>
    <br><br>
    {{message}}
    <div class="error" v-show="error.show">
      {{error.info}}
    </div>
  </div>
</template>

<script>
import Axios from 'axios'

export default {
  data() {
    return {
      message: '',
      error:{
        show: false,
        info: ''
      }
    }
  },
  mounted() {
    this.axios = Axios.create({
      timeout: 3000,
      baseURL: 'http://demo-api.geekfun.website'
    });
  
    this.axios.interceptors.request.use(
      config => config,
      error => {
        this.showError('请求异常')
        return Promise.reject(error);
      }
    );
  
    this.axios.interceptors.response.use(
      response => response, 
      error => { 
        this.showError('响应异常：' + error.message);
        return Promise.reject(error);
      }
    );
  },
  methods: {
    startRequest(){
      this.axios
        .get('ch11/slow.aspx')
        .then(response => this.message = response.data);
    },
    showError(info) {
      this.error.info = info;
      this.error.show = true;
      setTimeout(
        () => this.error.show = false,
        250000
      )
    }
  }
}
</script>
  <style>
    .error {
      position: fixed;
      z-index: 2000;
      left: 50%;
      top:50%;
      transform: translateX(-50%) translateY(-50%);
      text-align: center;
      border-radius: 10px;
      color:#FFF;
      background: rgba(17, 17, 17, 0.7);
      padding: 20px;
    }
  </style>